<template>
  <div id="content" class="dark-theme">
    <link href="/assstatic/css/common.css" rel="stylesheet" />
    <link href="/assstatic/css/mark-page.css" rel="stylesheet" />
    <link href="/assstatic/css/componentLibrary.css" rel="stylesheet" />
    <link href="/assstatic/css/getNext.css" rel="stylesheet" />
    <Dialogs v-show="getDialogs.status"/>
    <header-component
      :componentInfoHeader="componentInfoHeader"
      :showHead="showHead"
      :history="history"
      :curName="info.markName"
      :standard="info.markStandard"
      :shortcutkeys="shortcutkeys"
      @repulseMark="repulseMark"
      @save="save"
      @submit="submit"
    ></header-component>
    <div class="content-box">
      <div class="right-content">
        <div class="content-slot">
          <div class="slot-head">
            <div class="openSlotSelect" @click="openSlot" :class="{'active':isOpenSlot}">属性</div>
            <div class="slotSelectType" v-show="isOpenSlot">
              <span :class="{'active':slotSelectType == 1}" @click="setSlotSelectType(1)">包含</span>
              <span :class="{'active':slotSelectType == 2}" @click="setSlotSelectType(2)">不包含</span>
              <span @click="openSlot">×</span>
            </div>
          </div>
          <ul class="slot-list choose">
            <li
              v-for="(item,key) in slotList"
              class="list-item"
              :key="item+key"
              :class="{'active':selectedSlot.indexOf(item.ename) !== -1,'selecting':isOpenSlot}"
              @click="addSign(item)"
              :title="item.cname"
              :style="{background:item.color}"
            >
              <span v-show="item.shortKey && !isOpenSlot">{{ item.shortKey}}</span>
              {{item.cname}}
            </li>
          </ul>
        </div>
      </div>
      <div class="left-content" :class="{'active': isTiling}">
        <div class="content-area">
          <div class="top">
            <div class="progress">{{finishNum}}/{{files.length}}</div>
            <div v-show="isTiling" class="emptySelect" @click="completeCheck()">清空多选区域</div>
            <div v-show="isTiling" class="emptyAttribute" @click="clearAttribute()">清空属性</div>
            <select
              name
              id
              class="screen"
              @change="switchType($event.target.value)"
              @click="$event.target.value = 3"
            >
              <option
                :selected="showType === 3"
                value="3"
                style="display: none"
              >{{showType === 0 ? "全部" : (showType === 1 ? "有属性" : "无属性")}}</option>
              <!--解决无法点击统一个的问题-->
              <option
                :selected="showType === 0"
                value="0"
              >全部&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{files.length}}</option>
              <option :selected="showType === 1" value="1">有属性&nbsp;&nbsp;&nbsp; {{finishNum}}</option>
              <option :selected="showType === 2" value="2">无属性&nbsp;&nbsp;&nbsp; {{noAttribute}}</option>
            </select>
          </div>
          <div class="info-box">
            <div
              class="item"
              v-for="(item, key) in showFiles"
              :key="item+key"
              :class="{'checked': item.index  === currentKey || checkList[item.index]}"
              :id="'img' + item.index"
            >
              <label :for="key" class="select">
                <input
                  type="checkbox"
                  :id="key"
                  @click="setCheckList($event, item)"
                  :checked="checkList[item.index]"
                />
              </label>
              <div class="img-box">
                <div class="img-name" :title="item.name">{{item.index + 1}}. {{item.name}}</div>
                <div class="img">
                  <img
                    :src="imgProxy(item,item.url,item.index)"
                    :ref="item.index + 1"
                    @click="setKey(item.index)"
                    :class="{'check': item.index === currentKey}"
                  />
                  <!--imgProxy(item,item.url,item.id)   imgProxy(item,item.url,item.index)-->
                </div>
                <div class="attribute">
                  <div
                    v-for="(sign,index) in item.attribute"
                    class="sign"
                    :key="sign+index"
                    :style="getSignColor(sign)"
                    @click="removeSign(item.index,sign)"
                  >{{slotCache[sign] ? slotCache[sign].cname : ""}}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="zoom-area" @click="isTiling = !isTiling">
          <span>‖</span>
        </div>
      </div>
      <div class="middle-content" v-show="!isTiling">
        <div class="big-img" v-show="!isTiling && !isCheckBox">
          <div id="picview" class="picview">
            <img :src="src" name="viewArea" id="viewArea" draggable="false" @load="loadImg" />
          </div>
        </div>
        <div class="big-img" v-show="!isTiling && isCheckBox">
          <div class="title">
            <span>已选中 {{checkListNum}} 张图片，点击右侧按钮批量添加</span>
            <span class="complete" @click="completeCheck()">完成</span>
          </div>
          <div class="img active" :key="items+keys" v-for="(items, keys) in checkList">
            <img :src="items.url" />
          </div>
        </div>
      </div>
      <div class="getsuccess" v-if="history.getSuccess">
        <div class="bg"></div>
        <div class="showpop">
          <div class="applytask">领取成功!现在去做任务？</div>
          <div class="btn" id="btn">
            <a class="yes" @click="executNow">立即执行</a>
            <a class="no" @click="closeResult">暂不执行</a>
          </div>
        </div>
      </div>
      <div class="getsuccess" v-if="history.submitsuccess">
        <div class="bg"></div>
        <div class="showpop">
          <div class="applytask">提交成功！</div>
          <div class="btn" id="btn">
            <a class="yes" @click="joinTask">领取下一条</a>
            <a class="no" @click="closeResult">退出</a>
          </div>
        </div>
      </div>
      <div id="pop" v-if="history.hidePop">
        <div class="layer"></div>
        <div class="show_pop bdradius">
          <div class="poptitle">
            <span class="fs14_bold">申请任务</span>
          </div>
          <div id="pop_con">
            <div class="inputcon">
              <ul>
                <li>
                  <div class="label">任务类型</div>
                  <div class="lab_con">
                    <span :class="{select: task_type == 'mark'}" @click="changeTab('mark')">标注任务</span>
                    <span class="grey" style="display: none">检查任务</span>
                    <span :class="{select: task_type == 'check'}" @click="changeTab('check')">检查任务</span>
                  </div>
                </li>
                <li v-show="task_type == 'mark'">
                  <div class="label">申请数量</div>
                  <div class="lab_con">
                    <input
                      class="applyweight"
                      v-model="countVal"
                      id="apply-input"
                      type="number"
                      name="lab_val"
                      :placeholder="single_min +  '-'  + single_max"
                      v-show="task_type=='mark' && apply_type == 'custom'"
                    />
                    <select
                      class="applyweight"
                      name="apply-select"
                      id="apply-select"
                      v-model="countVal"
                      v-if="task_type=='mark' && apply_type == 'gradient'"
                    >
                      <option
                        :value="level"
                        :key="level + index"
                        v-for="(level,index) in count_level"
                      >{{level}}</option>
                    </select>
                  </div>
                </li>
              </ul>
            </div>
            <div class="btngroup">
              <a class="yes" @click="apply">确定</a>
              <a class="no" @click="closeResult">取消</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Header from "@/components/Header";
import Dialogs from "@/components/dialogs";
import {mapGetters} from 'vuex';
import $ from 'jquery';
import "../assets/js/zoom-marker";


export default {
  name: "MarkPage",
  data() {
    return {
      taskId: "",
      markTaskId: "",
      recheck: null,
      MytaskList: "",
      task: {},
      task_type: "mark",
      apply_type: "custom",
      single_min: 0,
      single_max: 0,
      count_level: [],
      countVal: null,
      currPage: 1,
      pageSize: 10,
      postData: {
        taskType: "", //任务类型：0-标注任务；1-检查任务；2-质检任务
        progressType: "0", //任务完成情况：0-未完成；1-已完成
        taskName: "", //任务名称
        taskStatus: ""
      },
      base: {
        batchId: "",
        step: "",
        lastMarkTaskId: null, // 上次标注的标注任务id 如果是检查任务，该值是标注id，如果是质检任务，可能是检查也可能是标注
        standard: "--" // 标注规范
      },
      componentInfoHeader: {
        // 头部参数
        shortcut: true,
        standard: true,
        history: false,
        repulse: false,
        theme: false
      },
      showHead: true, // 头部是否展示
      theme: false, // 当前皮肤
      shortcutkeys: [
        { key: "↑", value: "上一张" },
        { key: "↓", value: "下一张" },
        { key: "属性", value: "1、2、3、4、5、q、w、e、r、t、a、s、d、f、g" },
        { key: "多选", value: "Shift+左键" }
      ], // 快捷键
      info: {}, // 文件基本信息
      all: {}, // 当前任务的全部信息
      files: [], // 全部的文件列表 （图片信息）
      showFiles: [], // 当前展示的文件列表 （图片信息）
      checkList: {}, // 多选的map集合
      checkListNum: 0, // 多选了几张图片
      isCheckBox: false, // 代表是否多选
      isTiling: false, // 是否平铺
      src: "", // 当前选中图片地址
      currentKey: 0, // 当前图片的序号，针对所有的图片，而不是展示的
      isOpenSlot: false, // 是否打开筛选标签
      slotSelectType: 1, // 筛选类型
      showType: 0, // 0 全部 1 已经标注 2 未标注
      selectedSlot: [], // 当前选中的slot
      slotList: [], // 标签集合
      colorList: [
        "rgb(0,128,255)",
        "rgb(179,130,0)",
        "rgb(103,96,255)",
        "rgb(39,165,82)",
        "rgb(224,109,135)",
        "rgb(151,164,31)",
        "rgb(121,121,121)",
        "rgb(212,75,22)",
        "rgb(0,119,141)",
        "rgb(155,70,97)",
        "rgb(78,92,181)",
        "rgb(113,105,48)",
        "rgb(182,96,255)",
        "rgb(238,131,22)",
        "rgb(73,121,94)",
        "rgb(74,78,98)",
        "rgb(224,69,216)",
        "rgb(126,71,139)",
        "rgb(178,89,17)",
        "rgb(13,72,219)"
      ], // 颜色集合
      shortKey: [
        "1",
        "2",
        "3",
        "4",
        "5",
        "q",
        "w",
        "e",
        "r",
        "t",
        "a",
        "s",
        "d",
        "f",
        "g"
      ], // 快捷键集合
      slotCache: {}, // 处理过后 便于处理的 标签数据缓存
      shortKeyCache: {}, // 快捷键缓存
      radio: false, // 是否单选
      isSaving: false, // 是否正在保存
      lastSubmit: "", // 上次保存的内容
      isKeydownPrepare: true, // 是否可以使用快捷键
      showListIndex: [], // 展示图片的index集合
      lastSelect: [], // 选择的图片的操作集合
      history: {
        hidePop: false,
        getSuccess: false,
        submitsuccess: false
      }
    };
  },
  components: {
    Dialogs,
    "header-component": Header
  },
  created() {
    let self = this;
    //修改页面标题
    document.getElementsByTagName("title")[0].innerText = "图片挑选";
    //获取taskId
    self.taskId = self.Utils.getQueryStringArgs()["taskId"];
    //markTaskId
    self.markTaskId = self.Utils.getQueryStringArgs()["markTaskId"];
    // self.taskId = "CDF5F86585594DF58E45CD134CEF6737";
    // self.markTaskId = "C1786ACC41E84E0A8CFD3703E546F7E1";
    //复检功能参数获取
    if (self.Utils.getQueryStringArgs().recheck === "recheck") {
      self.recheck = 1;
    } else {
      self.recheck = 0;
    }
    self.setKeyDownEvent();
  },
  mounted() {
    $(document).ready(function() {
      $("#viewArea").zoomMarker({
        rate: 0.1
      });
    });
    this.init();
  },
  computed: {
    ...mapGetters(["getDialogs"]),
    finishNum: function() {
      // 查看标注完成个数
      var files = this.files,
        len = files.length,
        result = 0;
      if (len === 0) return "--";
      for (let i = 0; i < len; i++) {
        if (files[i].attribute.length > 0) {
          result++;
        }
      }
      return result;
    },
    noAttribute: function() {
      // 没有属性的标签个数
      let self = this;
      var files = self.files,
        len = files.length,
        result = 0;
      if (len === 0) return "--";
      for (var i = 0; i < len; i++) {
        if (files[i].attribute.length <= 0) {
          result++;
        }
      }
      return result;
    },
    markNum: function() {
      let self = this;
      var result = 0;
      if (self.history.showVersionInfo) {
        for (let i = 0; i < self.history.versionData.length; i++) {
          if (self.history.versionData[i].status === 1) {
            result++;
          }
        }
      } else {
        for (let i = 0; i < self.data.length; i++) {
          if (self.data[i].status === 1) {
            result++;
          }
        }
      }

      return result;
    }
  },
  methods: {
    closeResult: function() {
      this.Assapi.closeResult(this.base.step);
    },
    GetQueryString: function(name) {
      //流转任务时获取batchid
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },
    executNow() {
      let self = this;
      self.PageNav.load(1,self.pageSize,"/v1/web/my/task?dealType=info",self.postData,function(data) {
          if (data.list == undefined || data.list == null || data.list == "") {
            return;
          } else {
            if (data.count == self.MytaskList) {
              self.$message("任务下发中,请稍后点击！");
            } else {
              data.list.sort(function(a, b) {
                return b.createTime * 1 - a.createTime * 1;
              });
              self.markTaskId = data.list[0].markTaskId;
              var url ='/assets/home/mark-page/?taskId=' +this.taskId +'&markTaskId=' +self.markTaskId;
              window.open(url);
              self.closeResult();
            }
          }
        }
      );
    },
    getMytaskList() {
      let self = this;
      self.PageNav.load(
        1,
        self.pageSize,
        "/v1/web/my/task?dealType=info",
        self.postData,
        function(data) {
          if (data.list == undefined || data.list == null || data.list == "") {
            return;
          } else {
            self.MytaskList = data.count;
          }
        }
      );
    },
    doApply: function(taskId, step, count) {
      var self = this;
      var url =
        "/v1/be/task/apply?taskId=" +
        this.taskId +
        "&step=" +
        step +
        "&sync=true";
      if (step == 0) {
        // 标注
        var params = {};
        var data = [];
        var item = {};
        item.count = parseInt(count);
        // 此参数不可删除
        item.userid = "";
        data.push(item);
        params.data = data;
        params.hasCount = true;
        this.$api
          .method(url, JSON.stringify(params), "POST")
          .then(data => {
            if (data == undefined || data == "") {
              return;
            }
            //if (data.rt.status == 200) {
            if (
              data.rt.status == 200 &&
              eval("(" + data.data + ")")[0].count > 0
            ) {
              self.history.getSuccess = true;
              return;
            } else {
              if (data.rt.status == 400004) {
                self.$message.error("暂无可领取的任务");
                return;
              } else if (data.rt.status == 400005) {
                self.$message.error("请先完成已领任务");
                return;
              }
              self.$message.error("领取失败，请重新申请");
            }
          })
          .catch(err => {
            console.log(err);
          });
      } else if (step == 1) {
        // 检查
        let params = {
          data: [{ userid: "" }],
          hasCount: true
        };
        this.$api
          .method(url, JSON.stringify(params), "POST")
          .then(data => {
            if (data == null || data == "") {
              return;
            }
            if (
              data.rt.status == 200 &&
              eval("(" + data.data + ")")[0].count > 0
            ) {
              self.history.getSuccess = true;
              return;
            } else {
              if (data.rt.status == 400004) {
                self.$message.error("暂无可领取的任务");
                return;
              } else if (data.rt.status == 400005) {
                self.$message.error("请先完成已领任务");
                return;
              }
              self.$message.error("领取失败，请重新申请");
            }
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        self.$message.error("类型错误");
      }
    },
    // 加入团队
    joinTeam: function(teamId) {
      var self = this;
      var url = "/v1/marker-recruit/team/apply";
      this.$api
        .method(url, { team_id: teamId }, "POST")
        .then(data => {
          if (data == null || data == "") {
            return;
          }
          if (data.rt.status == 200) {
            self.$message("已申请");
          } else if (data.rt.status == 100005) {
            self.$message("已申请");
          } else if (data.rt.status == 100002) {
            self.$message("该团队不计划对外招募成员");
          } else {
            self.$message.error(data.data);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    apply: function() {
      var self = this;
      if (self.apply_type == "custom" && self.task_type == "mark") {
        // 自定义数量申请
        if (self.countVal == null || self.countVal == "") {
          if (!$("input[name='lab_val']").hasClass("err")) {
            $("input[name='lab_val']")
              .removeClass("yes")
              .addClass("err")
              .after("<div class='error'>请输入申请数量</div>");
          }
          return;
        }
        if (
          this.countVal < this.single_min ||
          this.countVal > this.single_max
        ) {
          this.countVal = this.single_min;
          if (!$("input[name='lab_val']").hasClass("err")) {
            $("input[name='lab_val']")
              .removeClass("yes")
              .addClass("err")
              .after(
                `<div class="error"><var>请输入</var> ${this.single_min} - ${this.single_max} <var>之间的数值</var></div>`
              );
          }
          return;
        }
      }
    },
    closePop: function() {
      this.history.hidePop = false;
    },
    // 加入任务
    joinTask: function() {
      var self = this;
      this.history.hidePop = true;
      this.getMytaskList();
      var proxyurl = "/v1/task/detail?taskId=";
      this.$api
        .method(proxyurl + this.taskId, "", "GET")
        .then(data => {
          if (data.rt.status == 200) {
            self.task = data.data;
            self.history.submitsuccess = false;
            // 检查用户是否有权限申请任务
            self.apply_type =
              self.task.countlevel == undefined || self.task.countlevel == ""
                ? "custom"
                : "gradient";
            if (self.apply_type == "gradient") {
              self.count_level = self.task.countlevel.split(";");
              // 排序
              self.count_level = self.count_level.sort(function(a, b) {
                return a - b;
              });
              self.countVal = self.count_level[0];
            }
            self.single_min = self.task.singlemin;
            self.single_max = self.task.singlemax;
          } else {
            self.$message.error("获取任务信息出错");
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    changeTab: function(index) {
      this.task_type = index;
    },
    // 设置keydown 事件
    setKeyDownEvent: function() {
      let self = this;
      document.addEventListener("keydown", function(e) {
        e = e || window.event;
        let code = e.keyCode || e.which || e.charCode,
          type = e.srcElement ? e.srcElement.className : e.target.className, // 出发所在位置;
          arr = [
            { keyCode: 49, key: "1" },
            { keyCode: 50, key: "2" },
            { keyCode: 51, key: "3" },
            { keyCode: 52, key: "4" },
            { keyCode: 53, key: "5" },
            { keyCode: 81, key: "q" },
            { keyCode: 87, key: "w" },
            { keyCode: 69, key: "e" },
            { keyCode: 82, key: "r" },
            { keyCode: 84, key: "t" },
            { keyCode: 65, key: "a" },
            { keyCode: 83, key: "s" },
            { keyCode: 68, key: "d" },
            { keyCode: 70, key: "f" },
            { keyCode: 71, key: "g" }
          ]; // 快捷键集合

        for (var i = 0; i < arr.length; i++) {
          if (!$(".uipop .layer").length) {
            // 可以使用快捷键(由于封装的方法存在缺陷，此处用是否存在dom来判断,俗称垃圾代码)
            self.shortKeyStop(e, code, type, arr[i].keyCode, arr[i].key);
          }
        }

        self.Assutils.shortKeyIfTrue(
          code === 38 && type !== "textarea",
          function() {
            // ↑
            self.preImage();
          },
          e
        );

        self.Assutils.shortKeyIfTrue(
          code === 40 && type !== "textarea",
          function() {
            // ↓
            self.nextImage();
          },
          e
        );
      });
    },
    // 阻止事件的封装方法
    shortKeyStop: function(e, code, type, keyCode, key) {
      let self = this;
      this.Assutils.shortKeyIfTrue(
        code === keyCode && type !== "textarea",
        function() {
          // a
          self.addSign(self.shortKeyCache[key]);
        },
        e
      );
    },
    // 多选完成
    completeCheck: function() {
      let self = this;
      self.$set(self, "checkList", {});
      self.isCheckBox = false;
      self.lastSelect = []; // 切换的时候,清空操作记录
    },
    // 清空选择区域的属性
    clearAttribute: function() {
      let self = this;
      for (var i in self.checkList) {
        try {
          self.checkList[i].attribute = [];
        } catch (e) {
          console.log(e);
        }
      }
      this.$forceUpdate();
    },
    // 切换选择的数据
    switchType: function(type) {
      let self = this;
      self.completeCheck();
      self.showType = Number(type);
      self.setShowList(); // 筛选数据
    },
    // 删除标签
    removeSign: function(key, sign) {
      let self = this;
      var target = self.files[key];
      var index = target.attribute.indexOf(sign);
      if (index > -1) {
        target.attribute.splice(index, 1);
      } else {
        self.$message.error("没找到此标签");
      }
    },
    // 获取标签颜色
    getSignColor: function(sign) {
      let self = this;
      var color = self.slotCache[sign] ? self.slotCache[sign].color : "";
      if (!color) {
        color = "#0080ff";
      }
      return "background:" + color;
    },
    // 添加标签
    addSign: function(item) {
      let self = this;
      if (!self.isOpenSlot) {
        // 没有打开
        self.onlyAddSign(item.ename);
      } else {
        // 打开筛选标签了
        if (self.slotSelectType === 1) {
          // 包含
          self.selectContain(item.ename);
        } else if (self.slotSelectType === 2) {
          // 不包含
          self.selectNoContain(item.ename);
        }
      }
    },
    // 单纯增加标签
    onlyAddSign: function(item) {
      let self = this;
      if (self.currentKey === "" && !self.isCheckBox) {
        // 非多选模式,且无单图出现
        this.$message("请选择将要标记的图片");
        return false;
      }

      if (!item) {
        this.$message("无效标签");
        return false;
      }

      if (!self.isCheckBox) {
        // 单图选择
        self.singleSelect(self.currentKey, item);
      } else {
        // 多图选择
        self.multipleSelect(item);
      }
    },
    // 单图选择
    singleSelect: function(key, item) {
      let self = this;
      var target = self.files[key];
      var index = target.attribute.indexOf(item);
      if (index > -1) {
        target.attribute.splice(index, 1);
      } else {
        if (!self.radio) {
          // 多选
          target.attribute.push(item);
        } else {
          target.attribute = [item];
        }
      }
    },
    // 多图选择
    multipleSelect: function(item) {
      let self = this;
      try {
        for (var i in self.checkList) {
          self.singleSelect(self.checkList[i].index, item);
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 包含标签筛选
    selectContain: function(item) {
      let self = this;
      self.setSelectedSlot(item);
      self.setShowList();
    },
    // 不包含标签筛选
    selectNoContain: function(item) {
      let self = this;
      self.setSelectedSlot(item);
      self.setShowList();
    },
    // 设置选择的标签
    setSelectedSlot: function(item) {
      let self = this;
      var target = self.selectedSlot;
      var index = target.indexOf(item);
      if (index > -1) {
        target.splice(index, 1);
      } else {
        target.push(item);
      }
    },
    // 打开标签筛选
    openSlot: function() {
      let self = this;
      self.isOpenSlot = !self.isOpenSlot;
      self.selectedSlot = [];
      self.setShowList();
    },
    // 设置当前筛选条件
    setSlotSelectType: function(data) {
      let self = this;
      self.slotSelectType = data;
      self.selectedSlot = [];
      self.setShowList();
    },
    // 根据条件筛选图片 （垃圾代码耦合很高）
    setShowList: function() {
      let self = this;
      var showType = self.showType; // 展示类型
      var isOpenSlot = self.isOpenSlot; // 是否开区筛选
      var slotSelectType = self.slotSelectType; // 筛选的条件
      var showList = [];
      if (showType === 0) {
        // 全部数据
        if (!isOpenSlot) {
          // 未开启
          showList = self.files;
          self.$set(self, "showFiles", showList);
          self.skipShowFirst(); // 自动加载展示数据序列的第一张图片
        } else {
          // 开启
          if (slotSelectType === 1) {
            // 拥有标签的时候
            self.getShowData(0, true, 1);
          } else if (slotSelectType === 2) {
            // 不拥有标签的时候
            self.getShowData(0, true, 2);
          }
        }
      } else if (showType === 1) {
        // 已经标注
        if (!isOpenSlot) {
          // 未开启
          self.getShowData(1, false);
        } else {
          // 开启
          if (slotSelectType === 1) {
            // 拥有标签的时候
            self.getShowData(1, true, 1);
          } else if (slotSelectType === 2) {
            // 不拥有标签的时候
            self.getShowData(1, true, 2);
          }
        }
      } else if (showType === 2) {
        // 未标注
        if (!isOpenSlot) {
          // 未开启
          self.getShowData(2, false);
        } else {
          // 开启
          if (slotSelectType === 1) {
            // 拥有标签的时候
            self.getShowData(2, true, 1);
          } else if (slotSelectType === 2) {
            // 不拥有标签的时候
            self.getShowData(2, true, 2);
          }
        }
      }
      // 针对showFiles 进行数据格式转换
      self.showFilesConvert();
    },
    // 获取展示的数据 type 全部数据的类型 open  是否开启 selectType 标签数据
    getShowData: function(type, open, selectType) {
      let self = this;
      var data = [];
      var selectedSlot = self.selectedSlot; // 选择的列表
      var need;
      self.files.forEach(function(value) {
        if (type === 0) {
          if (!open) {
            data.push(value);
          } else if (open && selectType === 1) {
            // 开启了，拥有才展示
            need = false;
            value.attribute.forEach(function(item) {
              if (selectedSlot.indexOf(item) > -1) {
                // 如果有
                need = true;
              }
            });
            if (need || selectedSlot.length === 0) {
              // 如果筛选条件为空也展示
              data.push(value);
            }
          } else if (open && selectType === 2) {
            need = true;
            value.attribute.forEach(function(item) {
              if (selectedSlot.indexOf(item) > -1) {
                // 如果有
                need = false;
              }
            });
            if (need) {
              // 因为是不拥有 所以可以不做判断
              data.push(value);
            }
          }
        } else if (type === 1) {
          if (!open) {
            if (value.attribute.length > 0) {
              data.push(value);
            }
          } else if (open && selectType === 1) {
            // 开启了，拥有才展示
            need = false;
            if (value.attribute.length > 0) {
              value.attribute.forEach(function(item) {
                if (selectedSlot.indexOf(item) > -1) {
                  // 如果有
                  need = true;
                }

                if (selectedSlot.length === 0) {
                  // 或者有标签时,晒选条件为空也可以
                  need = true;
                }
              });
            }
            if (need) {
              // 如果筛选条件为空也展示
              data.push(value);
            }
          } else if (open && selectType === 2) {
            need = false;
            if (value.attribute.length > 0) {
              need = true; // 有属性代表可以为true
              value.attribute.forEach(function(item) {
                if (selectedSlot.indexOf(item) > -1) {
                  // 如果有这个标签,则为false
                  need = false;
                }
              });

              if (selectedSlot.length === 0) {
                // 或者有标签时,晒选条件为空也可以
                need = true;
              }
            }
            if (need) {
              data.push(value);
            }
          }
        } else if (type === 2) {
          if (!open) {
            if (value.attribute.length === 0) {
              data.push(value);
            }
          } else if (open && selectType === 1) {
            // 开启了，拥有才展示
            need = false;
            if (value.attribute.length === 0 && selectedSlot.length === 0) {
              // 只有当图片没有属性，且筛选条件为空时
              need = true;
            }
            if (need) {
              // 不可能拥有 || selectedSlot.length === 0 哪怕筛选条件为空 也不能拥有
              data.push(value);
            }
          } else if (open && selectType === 2) {
            // 开启了 ，不拥有
            // need = false;
            if (value.attribute.length === 0) {
              // 因为是未标注 所以只需要这一个条件
              data.push(value);
            }
            // if (need) {
            //     data.push(value)
            // }
          }
        }
      });
      console.log(data);
      self.$set(self, "showFiles", data);
      self.skipShowFirst(); // 自动加载展示数据序列的第一张图片
      return data;
    },
    // 自动加载到 showList中的第一条数据的图片
    skipShowFirst: function() {
      let self = this;
      try {
        var index = self.showFiles[0].index;
        self.$nextTick(function() {
          self.setKey(index);
          self.skipImgPos(index); // 2019/7/9
        });
      } catch (e) {
        console.warn(e);
      }
    },
    // 设置当前图片的index 这个index 是针对所有的图片 而不是 展示的图片 所以取的地址应该是 整个 files 而不是 show
    setKey: function(index) {
      this.currentKey = index;
      this.src = this.files[index].url;
    },
    // 上一张可视图片
    preImage: function() {
      let self = this;
      var index = self.showListIndex.indexOf(this.currentKey);
      var targetIndex = self.showListIndex[index - 1];
      if (!targetIndex && targetIndex !== 0) {
        // 如果没找到 或者 已经是第一张  targetIndex <= -1
        this.$message("暂无上一张可视图片");
      } else {
        self.setKey(targetIndex);
        self.skipImgPos(targetIndex);
      }
    },
    // 下一张可视图片
    nextImage: function() {
      let self = this;
      var index = self.showListIndex.indexOf(this.currentKey);
      var targetIndex = self.showListIndex[index + 1];
      if (!targetIndex) {
        // 如果没找到 或者 超出长度  || targetIndex >= self.showFiles.length
        this.$message("暂无下一张可视图片");
      } else {
        self.setKey(targetIndex);
        self.skipImgPos(targetIndex);
      }
    },
    // 数据转换
    showFilesConvert: function() {
      let self = this;
      self.showListIndex = [];
      self.showFiles.forEach(function(value) {
        if (self.showListIndex.indexOf(value.index) === -1) {
          self.showListIndex.push(value.index);
        }
      });
      self.showListIndex.sort(function(a, b) {
        return a - b;
      });
    },
    // 图片加载完毕
    loadImg: function() {
      $("#viewArea").setImgPosition();
    },
    // 多选
    setCheckList: function(e, item) {
      if (e.shiftKey) {
        // 多选模式
        this.shiftSelectList(item);
      }

      var checkStatus = e.target.checked;
      if (checkStatus) {
        this.checkList[item.index] = item;
        this.lastSelect.push(item.index); // 操作的图片集合
      } else {
        delete this.checkList[item.index];
      }

      var checkAll = JSON.stringify(this.checkList);

      if (checkAll === "{}") {
        this.isCheckBox = false;
      } else {
        this.isCheckBox = true;
      }
      this.computedImg(); // 计算图片的数量
    },
    // shift 批量筛选
    shiftSelectList: function(item) {
      var lastSelect = this.lastSelect[this.lastSelect.length - 1];
      if (lastSelect !== undefined) {
        // 不为空
        if (lastSelect > item.index) {
          // 如果序号大于当前
          for (var i = item.index; i < lastSelect; i++) {
            if (this.showListIndex.indexOf(i) > -1) {
              // 说明当前下标在展示列表中
              this.checkList[i] = this.files[i];
            }
          }
        } else {
          for (var j = lastSelect; j < item.index; j++) {
            if (this.showListIndex.indexOf(j) > -1) {
              // 说明当前下标在展示列表中
              this.checkList[j] = this.files[j];
            }
          }
        }
      }
    },
    // 多张图片的数量
    computedImg: function() {
      try {
        this.checkListNum = Object.keys(this.checkList).length;
      } catch (e) {
        this.checkListNum = 0;
      }
    },
    // 图片代理 (需要增加额外的参数，防止多次重复加载，但是仍然会重复加载两次（可以用骚操作做处理）,好像有点问题)
    imgProxy: function(imgData, imgs, index) {
      if (!imgData.temStatus) {
        // 防止图片重复加载
        var img = new Image(),
          self = this;
        img.onload = function() {
          self.$refs[index + 1][0].src = imgs;
          imgData.temStatus = true;
          return imgs;
        };
        img.src = imgs;
        return "/assstatic/images/seat.svg";
      } else {
        return imgs;
      }
    },
    // 初始化
    init() {
      let self = this;
      // self.files = self.showFiles;
      this.Assapi.getFileListNew(
        {
          // 复检功能
          markTaskId: self.markTaskId,
          markFileId: "all",
          recheck: self.recheck
        },
        async function(info) {
          info = JSON.parse(info);
          var step = info.step;
          var pageElement = info.pageElement || {};
          self.files = self.dataHandle(info.files[0].defaultResult); // 数据处理增加index等

          if (step === 1) {
            // 检查环节有打回
            if (!self.recheck) {
              // 主平台复检
              self.componentInfoHeader.repulse = true;
            } else {
              self.componentInfoHeader.recheck = true;
            }
          } else if (step === 2) {
            if (!self.recheck) {
              // 主平台复检
              self.componentInfoHeader.repulse = true;
            } else {
              self.componentInfoHeader.recheck = true;
            }
          }

          self.info = info;
          self.slotList = pageElement.childLabel
            ? pageElement.childLabel.label
            : []; // 标签
          self.radio = pageElement.childLabel
            ? pageElement.childLabel.radio
            : false; // 单选
          await self.getCurrentResult(function(){
            // self.setShowList();
            // self.handleSign();
            // self.addScroll();
            // self.setInterval();
          }); // 获取最新结果
          self.setShowList();
          self.handleSign();
          self.addScroll();
          self.setInterval();
        }
      );
    },
    // 设置定时器
    setInterval: function() {
      let self = this;
      self.autoSaveInterval = setInterval(function() {
        // 20s一次 查看历史的时候跳过执行
        if (!self.isSaving) {
          self.save(true, true, function() {
            self.$message("自动保存成功！");
          }); // 自动，异步
        }
      }, 20000);
    },
    // 获取结果服务新数据
    async getCurrentResult(success) {
      let self = this;
      await this.Assapi.getCurrentResult(self.taskId, self.markTaskId, 0, function(info) {
        // console.log('获取最新结果',info);
        info = JSON.parse(info.resultText);
        self.files = self.dataHandle(info);
        // success?success():'';
      });
    },
    // 数据处理增加 index 等
    dataHandle: function(data) {
      if (Object.prototype.toString.call(data) === "[object Array]") {
        data.forEach(function(item, key) {
          if (item.index === undefined) {
            data[key].index = key;
          }
          if (!item.init) {
            data[key].url =
              "/v1/css/file/read?path=" +
              data[key].url;
            data[key].init = true;
          }
          if (item.temStatus) {
            // 设置每一次进来后的初始化
            item.temStatus = undefined;
          }
        });
        return data;
      } else {
        this.$message("数据错误");
        return data;
      }
    },
    // 处理 标签颜色
    handleSign: function() {
      let self = this;
      self.slotList.forEach(function(value) {
        // 第一次遍历去重颜色
        if (value.color) {
          var index = self.colorList.indexOf(value.color);
          self.colorList.splice(index, 1);
        }
      });

      self.slotList.forEach(function(value) {
        // 第一次遍历去重颜色
        if (!value.color) {
          if (self.colorList.length >= 1) {
            value.color = self.colorList.pop();
          } else {
            value.color = "rgb(224,109,135)";
          }
        }

        if (self.shortKey.length > 0) {
          // 增加快捷键名称
          value.shortKey = self.shortKey.shift();
          self.shortKeyCache[value.shortKey] = value; // 将快捷键缓存下来
          // self.shortcutkeys.push({
          //     key: value.shortKey,
          //     value: value.cname
          // })
        }
        self.slotCache[value.ename] = {
          color: value.color,
          cname: value.cname
        }; // 将标签数据缓存起来便于处理
      });
    },
    // 加载滚动条
    addScroll: function() {
      // slot-list
      // $(".slot-list").mCustomScrollbar({
      //   autoDraggerLength: true,
      //   scrollInertia: 250,
      //   mouseWheelPixels: 60
      // });
      // $(".shortcut .showBox .table").mCustomScrollbar({
      //   autoDraggerLength: true,
      //   scrollInertia: 250,
      //   mouseWheelPixels: 60
      // });

      // $(".slot-list").mCustomScrollbar("update");
    },
    // 跳转到指定图片位置
    skipImgPos: function(index) {
      try {
        var box = $(".info-box");
        var top = $("#img" + index).position().top + box.scrollTop();
        box.scrollTop(top);
      } catch (e) {
        console.warn(e);
      }
    },
    // 打回
    repulseMark: function() {
      var self = this;
      self.isKeydownPrepare = false;
      self.save(false, false, function() {
        var html =
          '<div class="popdis"><div class="con">\
                            <label>打回原因:</label>\
                            <textarea id="_contentRepulse" placeholder="请输入评价" style="resize: none; height: 90px;width: 290px;"></textarea>\
                        </div></div>';
        this.$store.dispatch("setdialogs", {
          title: "操作",
          content: html,
          status: true,
          issure: function() {
            var content = $("#_contentRepulse").val();
            content = content.replace(/^\s+|\s+$/g, "");
            if (content.length > 100 || content.length < 4) {
              self.$message("请输入规定范围文字个数4~100");
              return false;
            }

            if (self.info.step == 1) {
              this.Assapi.submitTask(
                self.markTaskId,
                JSON.stringify({ isQualified: 1, evaluate: content }),
                function() {
                  self.$message("打回成功...");
                  this.Assapi.closeResult(self.info.step);
                }
              );
            } else if (self.info.step === 2) {
              // 主平台复检
              this.Assapi.repulseTask(
                self.markTaskId,
                JSON.stringify({ isQualified: 1, evaluate: content }),
                function() {
                  self.$message("打回成功...");
                  self.closeResult();
                }
              );
            }
            self.isKeydownPrepare = true;
            return true;
          },
          cancel: function() {
            self.$store.dialogs.status = false;
            self.isKeydownPrepare = true;
            return true;
          }
        });
      });
    },
    // 保存 autoSave 自动保存 async 是否异步 success 成功回调
    save: function(autoSave, async, success) {
      let self = this;
      if (self.isSaving) {
        // 是否正在保存
        this.$message("结果正在保存，请稍后操作！");
        return false;
      }

      if (autoSave === undefined) {
        // 未传递 默认 自动保存
        autoSave = true;
      }

      if (async === undefined) {
        // 未传递 默认 异步保存
        async = true;
      }

      var params = {
        lastIndex: self.currentKey, // 当前标记的图片
        result: {
          markTaskFileId: "0",
          batchId: self.info.batchId,
          markTaskId: self.markTaskId,
          stamp: 0,
          resultText: JSON.stringify(self.files),
          autoSave: autoSave
        }
      };

      if (self.lastSubmit == JSON.stringify(self.files) && autoSave) {
        // 自动保存校验
        // this.$message("结果已保存！");
        return false;
      }

      self.isSaving = true;

      this.Assapi.saveResult(
        { markTaskId: self.markTaskId, markFileId: 0, recheck: self.recheck },
        params,
        function() {
          self.isSaving = false;
          self.lastSubmit = JSON.stringify(self.files); // 缓存本次保存的内容
          success ? success() : "";
        },
        async,
        function(errorInfo) {
          self.isSaving = false;
          self.$message.error(errorInfo);
        }
      );
    },
    // 提交
    submit: function() {
      let self = this;
      // 校验是否标注完成
      var files = self.files,
        len = files.length;
      if (len === 0) return "--";
      for (var i = 0; i < len; i++) {
        if (files[i].attribute.length === 0) {
          this.$message(
            "第" + (files[i].index + 1) + "张图片漏标属性，请补充完整"
          );
          self.showType = 2; // 切换到未标注
          self.setShowList(); // 展示未标注
          self.setKey(files[i].index); // 切换到具体的图片
          self.$nextTick(function() {
            $(".info-box").scrollTop(0);
          });
          return;
        }
      }

      self.save(false, true, function() {
        self.submitData(); // 保存成功后，提交
      });
    },
    //提交做的改变
    submitedClearInterval(){
      clearInterval(this.autoSaveInterval);
      this.history.submitsuccess = true;
      this.Assapi.closeResult(this.info.step);
    },
    submitedIsKeydownPrepare(){
      this.isKeydownPrepare = true;
    },
    // 数据提交
    submitData: function() {
      let self = this;
      self.isKeydownPrepare = false;
      if (self.info.step == 0) {
        // 标注提交
        this.$MessageBox.confirm("任务已完成，确认提交？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.Assapi.submitTask(self.markTaskId, "", function() {
              clearInterval(self.autoSaveInterval);
              self.history.submitsuccess = true;
            });
            self.isKeydownPrepare = true;
          })
          .catch(() => {
            self.isKeydownPrepare = true;
          });
      } else if (self.info.step == 1) {
        // 检查提交
        this.$store.dispatch("setdialogs", {
          step: 1,
          status: true,
          clearInterval:this.submitedClearInterval,
          markTaskId:this.markTaskId, 
          isKeydownPrepare:this.submitedIsKeydownPrepare
        });
      } else if (self.info.step == 2) {
        // 质检提交
        this.$store.dispatch("setdialogs", {
          step: 2,
          status: true,
          clearInterval:this.submitedClearInterval,
          markTaskId:this.markTaskId, 
          isKeydownPrepare:this.submitedIsKeydownPrepare
        });
      }
    }
  }
};
</script>